package com.wechat.controller.background;

import com.wechat.apidoc.background.WxBackgroundLoginInterface;
import com.wechat.utils.ActionResult;
import com.wechat.utils.CookieUtils;
import com.wechat.utils.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ycx on 2018/4/19.
 */
@RestController
@RequestMapping(value = "background")
public class WxBackgroundLoginController implements WxBackgroundLoginInterface {

    private static Logger logger = LoggerFactory.getLogger(WxBackgroundLoginController.class);

    @Override
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ActionResult login(String username, String password,
                              HttpServletRequest request, HttpServletResponse response) {

        logger.info("[后台登录接口]:{}", "username=" + username + ",password=" + password);

        ActionResult result = new ActionResult<>();
        try {
            if ("admin".equalsIgnoreCase(username) && "111111".equalsIgnoreCase(password)) {
                result.setSuccess(true);
                result.setMessage("后台登录成功");

                String uuid = UUIDUtils.getUUID();
                request.getSession().setAttribute("sessionToken", uuid);
                String domain = request.getServerName();
                // cookie有效期默认设置为1天
                CookieUtils.addCookie(request, response, "cookieToken", uuid, 86400, domain);
            } else {
                result.setSuccess(false);
                result.setMessage("后台登录失败");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("后台登录失败");

            logger.warn("[后台登录接口异常]：", e);
        }
        return result;
    }

}
